package com.mcxx.modules.common.service.impl;

import cn.hutool.core.date.DateUtil;
import com.google.common.base.Strings;
import com.mcxx.common.exception.BizException;
import com.mcxx.modules.common.service.FundpayStatisticService;
import com.mcxx.modules.base.service.read.AreaReadService;
import com.mcxx.modules.filemanage.easypoi.util.ExportExcelService;
import com.mcxx.modules.filemanage.file.service.FileService;
import com.mcxx.modules.miniSalvation.fundpay.entity.FundPayStatusEntity;
import com.mcxx.modules.miniSalvation.fundpay.service.read.FundPayReadService;
import com.mcxx.modules.statistics.dto.FundPayCityStateDTO;
import com.mcxx.modules.statistics.dto.FundPayCityStateExcelDTO;
import com.mcxx.modules.statistics.dto.FundpayStateDTO;
import com.mcxx.modules.statistics.param.StatisticParam;
import com.mcxx.modules.system.service.write.TaskExportWriteService;
import com.mcxx.modules.temporary.fundpay.service.read.TmpFundPayReadService;
import com.mcxx.util.AreaUtil;
import com.mcxx.util.CommonUtil;
import com.mcxx.util.Constant;
import com.mcxx.util.FailureCode;
import com.yinhai.ta404.component.audit.vo.ExcelInfo;
import com.yinhai.ta404.component.org.orguser.area.entity.TaAreaPo;
import com.yinhai.ta404.core.security.vo.UserAccountVo;
import com.yinhai.ta404.core.transaction.annotation.TaTransactional;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;


@Slf4j
@Service
@TaTransactional
public class FundpayStatisticServiceImpl implements FundpayStatisticService {

    private final static Logger logger = LoggerFactory.getLogger(FundpayStatisticServiceImpl.class);

    @Autowired
    private AreaReadService  areaReadService;
    @Autowired
    private AreaUtil areaUtil;
    @Autowired
    private FundPayReadService fundPayReadService;
    @Autowired
    private TmpFundPayReadService tmpFundPayReadService;
    @Resource
    private ExportExcelService exportExcelService;
    @Autowired
    private FileService fileService;
    @Autowired
    private TaskExportWriteService taskExportWriteService;
    @Override
    public List<FundPayCityStateDTO> getFundpayCreate(StatisticParam param) {

        if(CommonUtil.invalidArgs(param.getAreaCode())){
            param.setAreaCode("430000000000");
        }
        if(CommonUtil.invalidArgs(param.getMonth()) || param.getMonth().length() != 6 ||
                areaUtil.getLevelByAreaCode(param.getAreaCode()) > Constant.AreaLevel.COUNTY){
            throw new BizException(FailureCode.ERR_11300);
        }


        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        Date pdate = null;
        try {
            pdate = sdf.parse(param.getMonth() + "01");
        } catch (ParseException e) {
            e.printStackTrace();
            throw new BizException("-1", "时间参数格式错");
        }


        Calendar ca = Calendar.getInstance();
        ca.setTime(pdate);
        ca.add(Calendar.MONTH, -1);
        ca.set(Calendar.DATE, 1);

        List<FundPayStatusEntity> allFunds = new ArrayList<FundPayStatusEntity>();
        List<FundPayStatusEntity> basicFunds = fundPayReadService.getFundpayCreate(
                                            areaUtil.getValidCode(param.getAreaCode()),
                                            DateUtil.format(pdate, "yyyy-MM-dd"),
                                            DateUtil.format(ca.getTime(), "yyyy-MM-dd"));
        List<FundPayStatusEntity> tempFunds = tmpFundPayReadService.getTmpFundpayCreate(
                                            areaUtil.getValidCode(param.getAreaCode()),
                                            DateUtil.format(pdate, "yyyy-MM-dd"),
                                            DateUtil.format(ca.getTime(), "yyyy-MM-dd"));
        List<TaAreaPo> citys = areaReadService.getChildrenByLevel(areaUtil.getValidCode(AreaUtil.HUNANCODE),
                                        Collections.singletonList(Constant.AreaLevel.CITY));

        if(null != basicFunds)
            allFunds.addAll(basicFunds);
        if(null != tempFunds) {
            tempFunds.forEach((item) -> {
                item.setBusinessType(Constant.BusinessCode.LINSHI);
            });
            allFunds.addAll(tempFunds);
        }


        boolean existFund = false;
        List<FundPayCityStateDTO> funds = new ArrayList<FundPayCityStateDTO>();
        for(TaAreaPo city : citys){
            existFund = false;
            FundPayCityStateDTO fund = new FundPayCityStateDTO(city.getAreaCode(), city.getAreaName());
            String validCode = areaUtil.getValidCode(city.getAreaCode());
            for (FundPayStatusEntity item : allFunds) {
                if(item.getAreaCode().startsWith(validCode)){
                    existFund = true;
                    fund.setFundpayStatus(item.getAreaCode(), item.getAreaName(), getSerialOfFundpay(item),
                                        item.getStatus());
                }
            }

            if(existFund)
                funds.add(fund);
        }

        if(null != param.getStatus() && (param.getStatus().equals("0") || param.getStatus().equals("1"))){
            int status = Integer.parseInt(param.getStatus());
            Iterator<FundPayCityStateDTO> it = funds.iterator();
            while(it.hasNext()){
                FundPayCityStateDTO temp = it.next();
                List<FundpayStateDTO> fundpays = temp.getFundpays();
                Iterator<FundpayStateDTO> itFundPay = fundpays.iterator();
                while(itFundPay.hasNext()){
                    FundpayStateDTO fundpay = itFundPay.next();
                    if(fundpay.getStatus().size() != 13){
                        itFundPay.remove();
                        continue;
                    }


                    if(status == 0){
                        if(!fundpay.getStatus().subList(0, 11).contains(status)){
                            itFundPay.remove();
                        }
                    }
                    else{
                        if(fundpay.getStatus().subList(0, 11).contains(0)){
                            itFundPay.remove();
                        }
                    }
                }


                if(fundpays.isEmpty())
                    it.remove();
                else
                    temp.setFundpays(fundpays);
            }
        }
        return funds;
    }

    private int getSerialOfFundpay(FundPayStatusEntity fundpay){
        if(fundpay.getBusinessType().equals(Constant.BusinessCode.DIBAO)){
            if(fundpay.getStandType().equals(Constant.BusinessStandType.CITY_DIBAO))
                return FundpayStateDTO.FundSerial.SUB_CITY;
            else
                return FundpayStateDTO.FundSerial.SUB_COUNTRY;
        }

        if(fundpay.getBusinessType().equals(Constant.BusinessCode.TEKUN)){
            if(null == fundpay.getSupplyType() || null == fundpay.getCostType())
                return -1;

            if(fundpay.getStandType().equals(Constant.BusinessStandType.CITY_TEKUN)){
                if(fundpay.getSupplyType().equals(Constant.SupplyType.SUPPLY_FOCUS)){
                    if(fundpay.getCostType().equals(Constant.CareFeeType.TEKUN_BASE_CODE))
                        return FundpayStateDTO.FundSerial.POVERTY_CITY_FOCUS_BASIC;
                    else
                        return FundpayStateDTO.FundSerial.POVERTY_CITY_FOCUS_NURSING;
                }
                else{
                    if(fundpay.getCostType().equals(Constant.CareFeeType.TEKUN_BASE_CODE))
                        return FundpayStateDTO.FundSerial.POVERTY_CITY_DISPERSE_BASIC;
                    else
                        return FundpayStateDTO.FundSerial.POVERTY_CITY_DISPERSE_NURSING;
                }
            }
            else{
                if(fundpay.getSupplyType().equals(Constant.SupplyType.SUPPLY_FOCUS)){
                    if(fundpay.getCostType().equals(Constant.CareFeeType.TEKUN_BASE_CODE))
                        return FundpayStateDTO.FundSerial.POVERTY_COUNTRY_FOCUS_BASIC;
                    else
                        return FundpayStateDTO.FundSerial.POVERTY_COUNTRY_FOCUS_NURSING;
                }
                else{
                    if(fundpay.getCostType().equals(Constant.CareFeeType.TEKUN_BASE_CODE))
                        return FundpayStateDTO.FundSerial.POVERTY_COUNTRY_DISPERSE_BASIC;
                    else
                        return FundpayStateDTO.FundSerial.POVERTY_COUNTRY_DISPERSE_NURSING;
                }
            }
        }

        if(fundpay.getBusinessType().equals(Constant.BusinessCode.LINSHI)){
            if(null == fundpay.getPayWay())
                return -1;

            if(fundpay.getPayWay().equals(Constant.PayWay.BANK))
                return FundpayStateDTO.FundSerial.TEMP_BANK;
            else if(fundpay.getPayWay().equals(Constant.PayWay.CASH))
                return FundpayStateDTO.FundSerial.TEMP_CASH;
            else
                return FundpayStateDTO.FundSerial.TEMP_KIND;
        }

        return -1;
    }


    private String getCodeToString(Integer num){
        String str = null;
        if(num == 0){
            str = "未创建";
        }else if( num == 1){
            str = "已创建";
        }else{
            str = "无";
        }
        return str;
    }

    @Override
    public ExcelInfo exportFundpayCreate(StatisticParam param, UserAccountVo accountVo){
        List<FundPayCityStateExcelDTO> list = new ArrayList<>();
        Workbook workbook = null;
        ExcelInfo excelInfo = null;

        List<FundPayCityStateDTO> fundPayCityStateList = this.getFundPayCreatedInfo(param, accountVo);
        if(!fundPayCityStateList.isEmpty()){
            for(FundPayCityStateDTO dto:fundPayCityStateList){
                List<FundpayStateDTO> fundpays = dto.getFundpays();
                if(!fundpays.isEmpty()){
                    for(FundpayStateDTO fundpayStateDTO:fundpays){
                        FundPayCityStateExcelDTO fundPayCityStateExcelDTO = new FundPayCityStateExcelDTO();
                        fundPayCityStateExcelDTO.setCityName(dto.getAreaName());
                        fundPayCityStateExcelDTO.setCountyName(fundpayStateDTO.getAreaName());
                        List<Integer> status = fundpayStateDTO.getStatus();
                        fundPayCityStateExcelDTO.setDbnc(getCodeToString(status.get(0)));
                        fundPayCityStateExcelDTO.setDbcs(getCodeToString(status.get(1)));
                        fundPayCityStateExcelDTO.setJbfsnc(getCodeToString(status.get(2)));
                        fundPayCityStateExcelDTO.setJbfscs(getCodeToString(status.get(3)));
                        fundPayCityStateExcelDTO.setJbjznc(getCodeToString(status.get(4)));
                        fundPayCityStateExcelDTO.setJbjzcs(getCodeToString(status.get(5)));
                        fundPayCityStateExcelDTO.setZlfsnc(getCodeToString(status.get(6)));
                        fundPayCityStateExcelDTO.setZlfscs(getCodeToString(status.get(7)));
                        fundPayCityStateExcelDTO.setZljznc(getCodeToString(status.get(8)));
                        fundPayCityStateExcelDTO.setZljzcs(getCodeToString(status.get(9)));
                        fundPayCityStateExcelDTO.setYhff(getCodeToString(status.get(10)));
                        fundPayCityStateExcelDTO.setSwff(getCodeToString(status.get(11)));
                        fundPayCityStateExcelDTO.setXjff(getCodeToString(status.get(12)));
                        list.add(fundPayCityStateExcelDTO);
                    }
                }
            }
        }
        String title = fundPayCityStateList.get(0).getTitle();

        workbook = exportExcelService.exportWorkBook(FundPayCityStateExcelDTO.class,list,
                Strings.isNullOrEmpty(title) ? "名册生成情况统计信息" : title,"名册生成情况统计列表",false);

        if(null != workbook){
            Sheet sheet = workbook.getSheetAt(0);
            sheet.shiftRows(1,sheet.getLastRowNum(),3);
            Row rowOne = sheet.createRow(1);
            rowOne.setHeight((short) 500);
            for(int i=0;i<16;i++){
                rowOne.createCell(i);
            }

            Cell cellOne = rowOne.getCell(0);
            cellOne.setCellValue("市级");
            cellOne.getCellStyle().setAlignment(HorizontalAlignment.CENTER);
            cellOne.getCellStyle().setVerticalAlignment(VerticalAlignment.CENTER);
            cellOne = rowOne.getCell(1);
            cellOne.setCellValue("区县");
            cellOne.getCellStyle().setAlignment(HorizontalAlignment.CENTER);
            cellOne.getCellStyle().setVerticalAlignment(VerticalAlignment.CENTER);
            cellOne = rowOne.getCell(2);
            cellOne.setCellValue("最低生活保障");
            cellOne.getCellStyle().setAlignment(HorizontalAlignment.CENTER);
            cellOne.getCellStyle().setVerticalAlignment(VerticalAlignment.CENTER);
            cellOne = rowOne.getCell(4);
            cellOne.setCellValue("特困人员供养");
            cellOne.getCellStyle().setAlignment(HorizontalAlignment.CENTER);
            cellOne.getCellStyle().setVerticalAlignment(VerticalAlignment.CENTER);
            cellOne = rowOne.getCell(12);
            cellOne.setCellValue("临时救助");
            cellOne.getCellStyle().setAlignment(HorizontalAlignment.CENTER);
            cellOne.getCellStyle().setVerticalAlignment(VerticalAlignment.CENTER);

            Row rowTwo = sheet.createRow(2);
            rowTwo.setHeight((short) 500);
            for(int i=0;i<16;i++){
                rowTwo.createCell(i);
            }
            Cell cellTwo = rowTwo.getCell(2);
            cellTwo.setCellValue("低保金名册");
            cellTwo.getCellStyle().setAlignment(HorizontalAlignment.CENTER);
            cellTwo.getCellStyle().setVerticalAlignment(VerticalAlignment.CENTER);
            cellTwo = rowTwo.getCell(4);
            cellTwo.setCellValue("基本生活费名册");
            cellTwo.getCellStyle().setAlignment(HorizontalAlignment.CENTER);
            cellTwo.getCellStyle().setVerticalAlignment(VerticalAlignment.CENTER);
            cellTwo = rowTwo.getCell(8);
            cellTwo.setCellValue("照料护理费名册");
            cellTwo.getCellStyle().setAlignment(HorizontalAlignment.CENTER);
            cellTwo.getCellStyle().setVerticalAlignment(VerticalAlignment.CENTER);
            cellTwo = rowTwo.getCell(12);
            cellTwo.setCellValue("银行转账名册");
            cellTwo.getCellStyle().setAlignment(HorizontalAlignment.CENTER);
            cellTwo.getCellStyle().setVerticalAlignment(VerticalAlignment.CENTER);
            cellTwo = rowTwo.getCell(13);
            cellTwo.setCellValue("实物发放名册");
            cellTwo.getCellStyle().setAlignment(HorizontalAlignment.CENTER);
            cellTwo.getCellStyle().setVerticalAlignment(VerticalAlignment.CENTER);
            cellTwo = rowTwo.getCell(14);
            cellTwo.setCellValue("现金发放名册");
            cellTwo.getCellStyle().setAlignment(HorizontalAlignment.CENTER);
            cellTwo.getCellStyle().setVerticalAlignment(VerticalAlignment.CENTER);

            Row rowThree = sheet.createRow(3);
            rowThree.setHeight((short) 500);
            for(int i=0;i<16;i++){
                rowThree.createCell(i);
            }
            Cell cellThree = rowThree.getCell(2);
            cellThree.setCellValue("农村");
            cellThree.getCellStyle().setAlignment(HorizontalAlignment.CENTER);
            cellThree.getCellStyle().setVerticalAlignment(VerticalAlignment.CENTER);
            cellThree = rowThree.getCell(3);
            cellThree.setCellValue("城市");
            cellThree.getCellStyle().setAlignment(HorizontalAlignment.CENTER);
            cellThree.getCellStyle().setVerticalAlignment(VerticalAlignment.CENTER);
            cellThree = rowThree.getCell(4);
            cellThree.setCellValue("分散供养");
            cellThree.getCellStyle().setAlignment(HorizontalAlignment.CENTER);
            cellThree.getCellStyle().setVerticalAlignment(VerticalAlignment.CENTER);
            cellThree = rowThree.getCell(6);
            cellThree.setCellValue("集中供养");
            cellThree.getCellStyle().setAlignment(HorizontalAlignment.CENTER);
            cellThree.getCellStyle().setVerticalAlignment(VerticalAlignment.CENTER);
            cellThree = rowThree.getCell(8);
            cellThree.setCellValue("分散供养");
            cellThree.getCellStyle().setAlignment(HorizontalAlignment.CENTER);
            cellThree.getCellStyle().setVerticalAlignment(VerticalAlignment.CENTER);
            cellThree = rowThree.getCell(10);
            cellThree.setCellValue("集中供养");
            cellThree.getCellStyle().setAlignment(HorizontalAlignment.CENTER);
            cellThree.getCellStyle().setVerticalAlignment(VerticalAlignment.CENTER);


            CellRangeAddress region = new CellRangeAddress(1, 1, 2, 3);
            sheet.addMergedRegion(region);
            CellRangeAddress region1 = new CellRangeAddress(1, 1, 4, 11);
            sheet.addMergedRegion(region1);
            CellRangeAddress region2 = new CellRangeAddress(1, 1, 12, 14);
            sheet.addMergedRegion(region2);
            CellRangeAddress region3 = new CellRangeAddress(2, 2, 2, 3);
            sheet.addMergedRegion(region3);
            CellRangeAddress region4 = new CellRangeAddress(2, 2, 4, 7);
            sheet.addMergedRegion(region4);
            CellRangeAddress region5 = new CellRangeAddress(2, 2, 8, 11);
            sheet.addMergedRegion(region5);
            CellRangeAddress region6 = new CellRangeAddress(3, 3, 4, 5);
            sheet.addMergedRegion(region6);
            CellRangeAddress region7 = new CellRangeAddress(3, 3, 6, 7);
            sheet.addMergedRegion(region7);
            CellRangeAddress region8 = new CellRangeAddress(3, 3, 8, 9);
            sheet.addMergedRegion(region8);
            CellRangeAddress region9 = new CellRangeAddress(3, 3, 10, 11);


            sheet.addMergedRegion(region9);
            CellRangeAddress region10 = new CellRangeAddress(1, 4, 0, 0);
            sheet.addMergedRegion(region10);
            CellRangeAddress region11 = new CellRangeAddress(1, 4, 1, 1);
            sheet.addMergedRegion(region11);
            CellRangeAddress region12 = new CellRangeAddress(3, 4, 2, 2);
            sheet.addMergedRegion(region12);
            CellRangeAddress region13 = new CellRangeAddress(3, 4, 3, 3);
            sheet.addMergedRegion(region13);
            CellRangeAddress region14 = new CellRangeAddress(2, 4, 12, 12);
            sheet.addMergedRegion(region14);
            CellRangeAddress region15 = new CellRangeAddress(2, 4, 13, 13);
            sheet.addMergedRegion(region15);
            CellRangeAddress region16 = new CellRangeAddress(2, 4, 14, 14);
            sheet.addMergedRegion(region16);
            excelInfo = exportExcelService.exportExcelByWorkBook(workbook,list,"名册生成情况统计信息.xls");
        }

        return excelInfo;
    }


    @Override
    public List<FundPayCityStateDTO> getFundPayCreatedInfo(StatisticParam param, UserAccountVo accountVo) {
        long start = System.currentTimeMillis();

        if(CommonUtil.invalidArgs(param.getAreaCode())){
            param.setAreaCode(accountVo.getAreaCode());
        }
        if(CommonUtil.invalidArgs(param.getMonth()) || param.getMonth().length() != 6 ||
                areaUtil.getLevelByAreaCode(param.getAreaCode()) > Constant.AreaLevel.COUNTY){
            throw new BizException(FailureCode.ERR_11300);
        }


        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        Date pdate = null;
        try {
            pdate = sdf.parse(param.getMonth() + "01");
        } catch (ParseException e) {
            e.printStackTrace();
            throw new BizException("-1", "时间参数格式错");
        }


        Calendar ca = Calendar.getInstance();
        ca.setTime(pdate);
        ca.add(Calendar.MONTH, -1);
        ca.set(Calendar.DATE, 1);

        List<TaAreaPo> taAreaPos = new ArrayList<TaAreaPo>();
        String name = commonStatisticStart(param, accountVo, taAreaPos, null);

        List<FundPayStatusEntity> allFunds = new ArrayList<FundPayStatusEntity>();


        String validCode = areaUtil.getValidCode(AreaUtil.HUNANCODE);


        List<TaAreaPo> citys = areaReadService.getChildrenByLevel(areaUtil.getValidCode(AreaUtil.HUNANCODE),
                Collections.singletonList(Constant.AreaLevel.CITY));


        List<TaAreaPo> countyList = areaReadService.getChildrenByLevel(areaUtil.getValidCode(AreaUtil.HUNANCODE),
                Collections.singletonList(Constant.AreaLevel.COUNTY));


        List<TaAreaPo> validCounty = countyList.stream().filter(e -> !e.getAreaCode().endsWith("99900")).collect(Collectors.toList());

        long startTime = System.currentTimeMillis();

        List<FundPayStatusEntity> saveObjectList = fundPayReadService.getHasSaveObjectZone(areaUtil.getValidCode(param.getAreaCode()), DateUtil.format(pdate, "yyyy-MM-dd"));
        long execTime = System.currentTimeMillis() - startTime;
        logger.info("查询低保特困有在保对象的所有地区,用时：{}", execTime);


        List<FundPayStatusEntity> basicFunds = fundPayReadService.getCapitalFundPayCreate(areaUtil.getValidCode(param.getAreaCode()), DateUtil.format(pdate, "yyyy-MM-dd"));

        basicFunds.addAll(saveObjectList);
        allFunds.addAll(basicFunds);

        long startTime1 = System.currentTimeMillis();

        List<FundPayStatusEntity> saveObjectTempList = fundPayReadService.getTempHasSaveObjectZone(areaUtil.getValidCode(param.getAreaCode()), DateUtil.format(pdate, "yyyy-MM-dd"));
        long execTime1 = System.currentTimeMillis() - startTime1;
        logger.info("查询临时救助 有在保对象的所有地区,用时：{}", execTime1);
        List<FundPayStatusEntity> tempFunds = tmpFundPayReadService.getTmpFundPayCreateInfo(areaUtil.getValidCode(param.getAreaCode()), DateUtil.format(pdate, "yyyy-MM-dd"));
        allFunds.addAll(saveObjectTempList);
        allFunds.addAll(tempFunds);

        List<FundPayCityStateDTO> funds = new ArrayList<FundPayCityStateDTO>();
        for(TaAreaPo city : citys){
            FundPayCityStateDTO fund = new FundPayCityStateDTO(city.getAreaCode(), city.getAreaName());
            List<FundpayStateDTO> fundList = new ArrayList<>();
            for (TaAreaPo item : validCounty) {
                if (city.getAreaCode().equals(item.getParentId())) {
                    FundpayStateDTO fundpayStateDTO = new FundpayStateDTO(item.getAreaCode(), item.getAreaName());
                    fundList.add(fundpayStateDTO);
                }
                fund.setFundpays(fundList);
            }
            funds.add(fund);
        }

        for(FundPayCityStateDTO fundCity : funds){

            List<FundpayStateDTO> cityList = fundCity.getFundpays();

            List<FundpayStateDTO> results = new ArrayList<>();

            for (FundpayStateDTO obj : cityList) {
                FundpayStateDTO county = new FundpayStateDTO(obj.getAreaCode(), obj.getAreaName());
                String validCode1 = areaUtil.getValidCode(obj.getAreaCode());

                Map<String, List<FundPayStatusEntity>> areaCodeMap = allFunds.stream().collect(Collectors.groupingBy(FundPayStatusEntity::getAreaCode));
                List<FundPayStatusEntity> countyFunds = areaCodeMap.get(validCode1 + "000000");
                if (null == countyFunds)
                    continue;

                List<FundPayStatusEntity>  noRepeatFunds = distinctFunds(countyFunds);

                for (FundPayStatusEntity item : noRepeatFunds) {
                    county.setSerialStatus(getSerialOfFundpay(item), item.getStatus());
                }
                results.add(county);
            }
            fundCity.setFundpays(results);
            fundCity.setTitle(name + "发放名册生成情况统计表");
        }


        if(null != param.getStatus() && (param.getStatus().equals("0") || param.getStatus().equals("1"))){
            int status = Integer.parseInt(param.getStatus());
            Iterator<FundPayCityStateDTO> it = funds.iterator();
            while(it.hasNext()){
                FundPayCityStateDTO temp = it.next();
                List<FundpayStateDTO> fundpays = temp.getFundpays();
                Iterator<FundpayStateDTO> itFundPay = fundpays.iterator();
                while(itFundPay.hasNext()){
                    FundpayStateDTO fundpay = itFundPay.next();
                    if(fundpay.getStatus().size() != 13){
                        itFundPay.remove();
                        continue;
                    }


                    List<Integer> statusList = fundpay.getStatus();
                    Set<Integer> set = new TreeSet<>();
                    for (Integer obj: statusList) {
                        set.add(obj);
                    }
                    if(!set.contains(Integer.valueOf(param.getStatus()))){
                        itFundPay.remove();
                    }
                }
            }
        }
        logger.info("查询名册生成情况,总用时：{}", System.currentTimeMillis() - start);
        return funds;
    }


    private List<FundPayStatusEntity> distinctFunds(List<FundPayStatusEntity> countyFunds) {
        List<FundPayStatusEntity> noRepeat = new ArrayList<>();
        Map<String,List<FundPayStatusEntity>> sameCountyMap = countyFunds.stream()
                .collect(Collectors.groupingBy(e -> e.getAreaCode() + e.getBusinessType() + e.getStandType() + e.getSupplyType() + e.getCostType() + e.getPayWay()));
        Set<String> keySet = sameCountyMap.keySet();
        for (String key : keySet) {
            List<FundPayStatusEntity> groupList = sameCountyMap.get(key);
            if (groupList.size() > 1) {
                Map<Integer,List<FundPayStatusEntity>> statusMap = groupList.stream()
                        .collect(Collectors.groupingBy(FundPayStatusEntity::getStatus));
                List<FundPayStatusEntity> keyList = new ArrayList<>();
                if (null != statusMap.get(-1) && statusMap.get(-1).size() > 0) {
                    keyList.add(statusMap.get(-1).get(0));
                }
                if (null != statusMap.get(0) && statusMap.get(0).size() > 0) {
                    if (!keyList.isEmpty())
                        keyList.remove(0);
                    keyList.add(statusMap.get(0).get(0));
                }
                if (null != statusMap.get(1) && statusMap.get(1).size() > 0) {
                    if (!keyList.isEmpty())
                        keyList.remove(0);
                    keyList.add(statusMap.get(1).get(0));
                }
                noRepeat.addAll(keyList);
            } else {
                noRepeat.addAll(groupList);
            }
        }
        return noRepeat;
    }



    public String commonStatisticStart(StatisticParam param, UserAccountVo accountVo, List<TaAreaPo> taAreaPos,
                                       List<Integer> levels){
        if(CommonUtil.invalidArgs(param.getMonth()) || param.getMonth().length() != 6) {
            throw new BizException(FailureCode.ERR_10001);
        }


        if(CommonUtil.invalidArgs(param.getAreaCode())){
            param.setAreaCode(accountVo.getAreaCode());
        }



        TaAreaPo curTaAreaPo = null;
        StringBuilder name= new StringBuilder();
        List<String> areaCodes = areaUtil.getNodeTreePathFromRoot(param.getAreaCode());
        for(String code : areaCodes){
            TaAreaPo taAreaPro = areaReadService.getAreaByCode(code);
            if(null != taAreaPro)
                name.append(taAreaPro.getAreaName());

            if(code.equals(param.getAreaCode())){
                curTaAreaPo = taAreaPro;
            }
        }

        if(null == curTaAreaPo){
            throw new BizException(FailureCode.ERR_100001);
        }

        name.append(param.getMonth().substring(0, 4)).append("年").append(param.getMonth().substring(4)).append("月");



        if(null != taAreaPos)
            taAreaPos.add(curTaAreaPo);

        if(null != levels && null != taAreaPos){
            levels.add(curTaAreaPo.getAreaLevel());
            if(curTaAreaPo.getAreaLevel().equals(Constant.AreaLevel.PROVINCE)){
                taAreaPos.addAll(areaReadService.getChildrenByLevel(
                        areaUtil.getValidCode(curTaAreaPo.getAreaCode(), curTaAreaPo.getAreaLevel()),
                        Arrays.asList(curTaAreaPo.getAreaLevel() + 1, curTaAreaPo.getAreaLevel() + 2)));
                levels.add(curTaAreaPo.getAreaLevel() + 1);
                levels.add(curTaAreaPo.getAreaLevel() + 2);
            }
            else{
                if (curTaAreaPo.getAreaLevel() < Constant.AreaLevel.COMMUNITY){
                    taAreaPos.addAll(areaReadService.getChildrenByLevel(
                            areaUtil.getValidCode(curTaAreaPo.getAreaCode(), curTaAreaPo.getAreaLevel()),
                            Collections.singletonList(curTaAreaPo.getAreaLevel() + 1)));
                    levels.add(curTaAreaPo.getAreaLevel() + 1);
                }
            }

            if(taAreaPos.isEmpty() || levels.isEmpty() || name.toString().isEmpty()){
                throw new BizException(FailureCode.ERR_100002);
            }
        }

        return name.toString();
    }
}
